package sw.controller;



import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import sw.entity.Books;
import sw.entity.Student;
import sw.repo.BooksRepository;
import sw.repo.StudentRepository;

@Controller
public class bringController {

	@Autowired
	private BooksRepository booksRepo;
	
	@Autowired
	private StudentRepository studentRepo;
	
	@GetMapping("/bring/{id}")
	public String bringHome(@PathVariable Long id,Model model){
		model.addAttribute("idd", id);
		return "/bring";
	}
	
	@PostMapping("/bringPost/{id}")
	public String bringPost(@PathVariable Long id,Student student){
		Books book = booksRepo.findOne(id);
		book.setStudent(student);
		book.setBring(1L);
		//booksRepo.save(book);
		studentRepo.save(student);
		return "redirect:/";
	}
	
	@GetMapping("/bringM")
	public String bringManage(Model model){
		List<Books> books=new ArrayList<Books>();
		Iterable<Books> bok=booksRepo.findAll();
		for(Books i:bok){
			if(i.getBring()!=null){
				books.add(i);
			}
		}
		model.addAttribute("books",books);
		return "/bringM";
	}
	
	
	@GetMapping("/return/{id}")
	public String returnBook(@PathVariable Long id){
		Books book = booksRepo.findOne(id);
		book.setBring(null);	
//		studentRepo.delete(book.getStudent());
		book.setStudent(null);
	    booksRepo.save(book);
		return "redirect:/bringM";
	}
	
}
